<?php 
/**
 * mysqli驱动
 * @author Yuwei(yuwei1122@gmail.com)
 *
 */
class BluePhp_Library_Db_Drives_Mysqli
{
	/**
	 * 服务器连接
	 * @var unknown_type
	 */
	protected static $_connectionRead;
	
	protected static $_connectionWrite;
	
	/**
	 * 构造函数
	 */
	public function __construct()
	{
		$db = json_decode(DB);
		if(!self::$_connectionRead && isset($db->read))
		{
			$read = $db->read;
			//读
			self::$_connectionRead = mysqli_connect($read->DB_HOST,$read->DB_USER,$read->DB_PWD,$read->DB_NAME,$read->DB_PORT) or die('db error');
			mysqli_query(self::$_connectionRead,'set NAMES '.isset($read->DB_ENCODE)?$read->DB_ENCODE:'utf8');
		}
		if(!self::$_connectionWrite && isset($db->write))
		{
			$write = $db->write;
			//写
			self::$_connectionWrite = mysqli_connect($write->DB_HOST,$write->DB_USER,$write->DB_PWD,$write->DB_NAME,$write->DB_PORT) or die('db error');
			mysqli_query(self::$_connectionWrite,'set NAMES '.isset($write->DB_ENCODE)?$write->DB_ENCODE:'utf8');
		}
		else if(isset($db->read))
			self::$_connectionWrite = self::$_connectionRead;
	}
	
	/**
	 * 查询
	 * @param unknown_type $sql
	 * @return object|boolean
	 */
	public function select($sql)
	{
		$result = mysqli_query(self::$_connectionRead,$sql);
		if($result)
		{
			$back = array();
			while ($row = mysqli_fetch_array($result))
				$back[] = $row;
			return $back;
		}
		return false;
	}
	
	/**
	 * 新增
	 * @param unknown_type $sql
	 * @return number|boolean
	 */
	public function insert($sql)
	{
		$result = mysqli_query(self::$_connectionWrite,$sql);
		if($result)
			return mysqli_insert_id(self::$_connectionWrite);
		return false;
	}
	
	/**
	 * 修改
	 * @param unknown_type $sql
	 * @param unknown_type $num 为true时返回受影响的行数
	 */
	public function update($sql,$num = false)
	{
		$result = mysqli_query(self::$_connectionWrite,$sql);
		if ($result)
		{
			if($num)
				return mysqli_affected_rows(self::$_connectionWrite);
			return true;
		}
		return false;
	}
	
	/**
	 * 删除
	 * @param unknown_type $sql
	 */
	public function delete($sql)
	{
		$result = mysqli_query(self::$_connectionWrite,$sql);
		if ($result)
			return true;
		return false;
	}
	
	/**
	 * 总数
	 * @param unknown_type $sql
	 */
	public function count($sql)
	{
		$result = mysqli_query(self::$_connectionRead,$sql);
		if ($result)
		{
			$row = mysqli_fetch_array($result);
			return (int)$row['count'];
		}
		return false;
	}
	
	/**
	 * 执行sql
	 * @param unknown_type $sql
	 */
	public function sql($sql)
	{
		$sqlArray = explode(' ', trim($sql));
		switch(strtolower($sqlArray[0]))
		{
			case 'select':
				return $this->select($sql);
			break;
			case 'insert':
				return $this->insert($sql);
			break;
			case 'update':
				return $this->update($sql);
			break;
			case 'delete':
				return $this->delete($sql);
			break;
		}
	}
}
?>